package com.zhupanlin.order.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.zhupanlin.order.bean.Order;
import com.zhupanlin.order.feign.ProductFeignClient;
import com.zhupanlin.order.service.OrderService;
import com.zhupanlin.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * 描述信息：
 *
 * @author zhupanlin
 * @version 1.0
 * @date 2025/1/23 15:14
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;
    
    @Autowired
    private ProductFeignClient productFeignClient;

    @SentinelResource(value = "createOrder", blockHandler = "createOrderFallback")
    @Override
    public Order createOrder(Long productId, Long userId) {

        // RestTemplate 获取数据
        // Product product = getProductFromRemoteLoadBalanceAnnotation(productId);
        
        // 使用 Feign 获取数据
        Product product = productFeignClient.getProductById(productId);

        Order order = new Order();
        order.setId(1L);
        order.setUserId(userId);
        // 总金额
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setAddress("anywhere");
        order.setNickname("zhangsan");
        // 远程查询商品列表
        order.setProductList(Arrays.asList(product));
        return order;
    }
    
    public Order createOrderFallback(Long productId, Long userId, BlockException e) {
        
        Order order = new Order();
        
        order.setId(productId);
        order.setTotalAmount(new BigDecimal(0));
        order.setUserId(userId);
        order.setNickname("未知用户");
        order.setAddress("异常信息: " + e.getClass());
        
        return order;
        
    }

    // 直接获取全部的地址
    private Product getProductFromRemote(Long productId) {
        // 1. 获取到商品服务所在到所有机器 IP + Port
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;
        log.info("远程请求:{}", url);


        // 2.给远程发送请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }


    /**
     * 负载均衡版本
     * @param productId
     * @return
     */
    private Product getProductFromRemoteLoadBalance(Long productId) {
        // 1. 获取到商品服务所在到所有机器 IP + Port
        ServiceInstance instance = loadBalancerClient.choose("service-product");
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;
        log.info("远程请求:{}", url);


        // 2.给远程发送请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    /**
     * 基于 @LoadBalanced 注解实现负载均衡
     * LoadBalance 会根据服务名去请求注册中心获得地址 进行替换
     * @param productId
     * @return
     */
    private Product getProductFromRemoteLoadBalanceAnnotation(Long productId) {
        String url = "http://service-product/product/" + productId;
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }



}